package com.wish233.retry.impl;

import com.github.rholder.retry.*;
import com.wish233.model.rpc.RpcResponse;
import com.wish233.retry.RetryStrategy;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

/**
 * @author WHH
 * 固定间隔重试
 */
@Slf4j
public class FixedIntervalRetryStrategy implements RetryStrategy {
    @Override
    public RpcResponse retry(Callable<RpcResponse> callable) throws Exception {
        Retryer<RpcResponse> retryer = RetryerBuilder.<RpcResponse>newBuilder()
                .retryIfException()
                //间隔三秒
                .withWaitStrategy(WaitStrategies.fixedWait(3L, TimeUnit.SECONDS))
                //最多尝试4次
                .withStopStrategy(StopStrategies.stopAfterAttempt(4))
                .withRetryListener(new RetryListener() {
                    @Override
                    public <V> void onRetry(Attempt<V> attempt) {
                        log.info("重试次数 {}", attempt.getAttemptNumber());
                        log.info("重试时长 {}ms", attempt.getDelaySinceFirstAttempt());
                    }
                })
                .build();
        return retryer.call(callable);
    }
}
